package top.resty.erp.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.resty.erp.commont.VOBrandAndVariety;
import top.resty.erp.domain.Variety;
import top.resty.erp.service.VarietyService;
import top.resty.erp.util.LayuiJson;

import java.util.ArrayList;
import java.util.List;

/**
 * <pre>
 *
 * </pre>
 *
 * @author : resty
 * @date : 2021年03月22 11:51
 */
@Controller
@RequestMapping("/variety")
public class VarietyController {
	
	@Autowired
	private VarietyService varietyService;
	
	
	@RequestMapping("/forBrandId")
	@ResponseBody
	public List<Variety> getVarietiesForBrandId(Integer brandId){
		return varietyService.getVarietyForBrandId(brandId);
	}
	
	@RequestMapping("/update")
	@ResponseBody
	public String updateVariety(Variety variety){
		return varietyService.updateVariety(variety)?"成功":"失败";
	}
	
	@RequestMapping("/del")
	@ResponseBody
	public String deleteVariety(Integer id){
		return varietyService.deleteVariety(id)?"success":"fail";
	}
	
	
	
	@RequestMapping("/all")
	@ResponseBody
	public LayuiJson<VOBrandAndVariety> getAllBrandAndVarieties(Integer brandId,Integer page,Integer limit){
		Page<Object> objects = PageHelper.startPage(page, limit);
		System.out.println("VarietyController  --  getAllBrandAndVarieties -- brandId = " + brandId);
		if("undefined".equals(brandId)){
			brandId = 0 ;
		}
		List<VOBrandAndVariety> list = varietyService.getBrandAndVarieties(brandId);
		List<VOBrandAndVariety> list1 = new ArrayList<>();
		LayuiJson layuiJson = new LayuiJson();
		if(brandId == 0 ){
			for (VOBrandAndVariety voBrandAndVariety : list) {
				if (voBrandAndVariety.getVarietyName()==null){
					voBrandAndVariety.setVarietyName("当前品牌下没有品种分类,请及时添加品种.勿直接修改.");
				}
			}
			layuiJson.setCount((int) objects.getTotal());
			list1.addAll(list);
		}else{
			for (int i = 0; i < list.size(); i++) {
				VOBrandAndVariety voBrandAndVariety = list.get(i);
				System.out.println(voBrandAndVariety);
				if (voBrandAndVariety.getId()!=null){
					list1.add(voBrandAndVariety);
				}
			}
			layuiJson.setCount(varietyService.queryBrandIdCountsForVarieties(brandId));
		}
		layuiJson.setData(list1);
		return layuiJson;
	}
	
	
	@RequestMapping("/add")
	public String saveVriety(Variety variety, Model model){
		String s = varietyService.saveVariety(variety) ? "成功" : "失败";
		model.addAttribute("msg", s);
		
		return "man/brand";
	}
	
	
}
